package gwtgaetools.shared.model;

import java.util.ArrayList;

import javax.jdo.annotations.Extension;
import javax.jdo.annotations.IdGeneratorStrategy;
import javax.jdo.annotations.IdentityType;
import javax.jdo.annotations.Inheritance;
import javax.jdo.annotations.InheritanceStrategy;
import javax.jdo.annotations.PersistenceCapable;
import javax.jdo.annotations.Persistent;
import javax.jdo.annotations.PrimaryKey;

import com.google.gwt.user.client.rpc.IsSerializable;

@PersistenceCapable(identityType = IdentityType.APPLICATION)
@Inheritance(strategy = InheritanceStrategy.SUBCLASS_TABLE)
public abstract class BaseObject2<T extends BaseObject2<T>> implements
	IsSerializable {

    @PrimaryKey
    @Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
    @Extension(vendorName = "datanucleus", key = "gae.encoded-pk", value = "true")
    private String id;

    public String getId() {
	return id;
    }

    public void setId(String id) {
	this.id = id;
    }

    public int index() {
	return -1;
    }

    public BaseObject2(T in) {
	this();
	in.copyFieldsTo(this);
    }

    public BaseObject2() {
    }

    public void copyFieldsTo(BaseObject2<T> destination) {
    }

    public static int maxIndex(ArrayList<? extends BaseObject2<?>> objs) {
	int i = 0;
	for (BaseObject2<?> obj : objs)
	    if (obj.index() > i)
		i = obj.index();
	return i;
    }

    public ArrayList<String> keys() {
	ArrayList<String> out;
	if (parent() != null)
	    out = parent().keys();
	else
	    out = new ArrayList<String>();
	out.add(0, getId());
	return out;
    }

    public abstract BaseObject2<?> parent();

}
